package com.yimixian.app.store;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.address.ShortAddress;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.MarkLocationMapActivity;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.location.LocatedListener;
import com.yimixian.app.location.LocationProvider;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.Store;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.rest.api.AddressAPI;
import com.yimixian.app.ui.BaseHttpFragment;
import com.yimixian.app.ui.ProgressDialogFragment;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.UiUtils;

import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;


public class StoreDetailFragment extends BaseHttpFragment {

    @InjectView(R.id.store_name_text)
    TextView mStoreNameText;
    @InjectView(R.id.store_business_hours_text)
    TextView mStoreBusinessHoursText;
    @InjectView(R.id.store_address_text)
    TextView mStoreAddressText;
    @InjectView(R.id.store_distance_text)
    TextView mStoreDistanceText;
    @InjectView(R.id.store_notification_text)
    TextView mStoreNotificationText;
    @InjectView(R.id.check_location_text)
    TextView mCheckLocationText;
    @InjectView(R.id.check_location_image)
    ImageView mCheckLocationImage;
    @InjectView(R.id.detail_button)
    TextView mDetailButton;
    @InjectView(R.id.phone_button)
    TextView mPhoneButton;
    @InjectView(R.id.content_frame)
    View mContentFrame;

    private AddressAPI mAddressAPI;
    private Store mStore;
    private String mStoreId;
    private YmxDataService mYmxDataService;
    private ProgressDialogFragment mProgressDialog;
    private DataManager mDataManager;
    private Address mAddress;
    private int upLoadStoreId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_store_detail, null);
        initData(view);
        return view;
    }

    void initData(View view){
        ButterKnife.inject(this, view);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mStore = (Store) bundle.get(StoreDetailActivity.EXTRA_STORE);
        }else if (isAdded()){
            getActivity().finish();
            return;
        }

        if (mStore != null) {
            upLoadStoreId = mStore.id;
            onStoreFetched();
        } else {
            mStoreId = bundle.getString(StoreDetailActivity.EXTRA_STORE_ID);
            if (TextUtils.isEmpty(mStoreId) && isAdded()) {
                getActivity().finish();
                return;
            }
            upLoadStoreId = Integer.parseInt(mStoreId);
            mProgressDialog = UiUtils.showProgressDialog(getActivity(),
                    getString(R.string.loading));
            mYmxDataService = YmxDataService.getInstance();
            mDataManager = DataManager.getInstance();
                LocationProvider.getInstance().startBaiduLocated(false, new LocatedListener() {

                    @Override
                    public void locatedSuccessListener(BDLocation location) {
                        if (location == null) {
                            fetchPickUpStore();
                            return;
                        }
                        mAddress = new Address();
                        mAddress.city = location.getCity();
                        mAddress.latitude = String.valueOf(location.getLatitude());
                        mAddress.longitude = String.valueOf(location.getLongitude());
                        fetchPickUpStore();
                    }

                    @Override
                    public void locatedSuccessGeoPoiInfoListener(PoiInfo poiInfo) {

                    }

                    @Override
                    public void locatedFailedListener() {
                        fetchPickUpStore();
                    }

                    @Override
                    public void locatedFailedGeoPoiInfoListener() {

                    }
                });
        }
    }

    private void onStoreFetched() {
        mStoreNameText.setText(mStore.name);
        mStoreBusinessHoursText.setText(mStore.businessHours);
        mStoreAddressText.setText(mStore.address);
        mStoreDistanceText.setText(mStore.distance);
        if(TextUtils.isEmpty(mStore.notification)) {
            mStoreNotificationText.setText("店面暂无提示信息");
        } else {
            mStoreNotificationText.setText(mStore.notification);
        }
        if (TextUtils.isEmpty(mStore.tel)) {
            mPhoneButton.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(mStore.tel)) {
            mPhoneButton.setVisibility(View.GONE);
        }
        if (mStore.coordinate == null) {
            mCheckLocationText.setVisibility(View.GONE);
            mCheckLocationImage.setVisibility(View.GONE);
        }
    }

    private void fetchPickUpStore() {
        mContentFrame.setVisibility(View.INVISIBLE);
        mYmxDataService
                .getPickUpStoreGoodsByStoreId(mStoreId,
                        DataManager.getInstance().<String> get(CacheKeys.TOKEN),
                        mAddress != null ? mAddress.longitude : "",
                        mAddress != null ? mAddress.latitude : "")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<Store>() {
                            @Override
                            public void call(Store store) {
                                UiUtils.dismiss(mProgressDialog);
                                mStore = store;
                                mContentFrame.setVisibility(View.VISIBLE);
                                onStoreFetched();
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                UiUtils.dismiss(mProgressDialog);
                                UiUtils.toastError(getActivity(), throwable);
                            }
                        }
                );
    }

    @OnClick({
            R.id.phone_button
    })
    public void onPhoneButtonClicked(final View view) {
        MobclickAgent.onEvent(getActivity(), StatConstants.STORE_DETAIL_CONTACT_CLICK);
        String number = mStore.tel;
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
        startActivity(intent);
    }

    @OnClick({
            R.id.detail_button
    })
    public void onDetailButtonClicked(final View view) {
        MobclickAgent.onEvent(getActivity(), StatConstants.STORE_DETAIL_SELECT_CLICK);
        fetchData(true, null);
    }

    @OnClick({
            R.id.check_location_image, R.id.check_location_text
    })
    public void onCheckLocationButtonClicked(final View view) {
        if (isAdded()){
            MobclickAgent.onEvent(getActivity(), StatConstants.STORE_DETAIL_IN_MAP_CLICK);
            Intent intent = new Intent(getActivity(), MarkLocationMapActivity.class);
            intent.putExtra(MarkLocationMapActivity.EXTRA_COORDINATE, mStore.coordinate);
            startActivity(intent);
        }
    }

    @Override
    public void initRequestAPI(String requestKeys) {
        mAddressAPI = new AddressAPI(DataManager.getInstance()
                .<String>get(CacheKeys.TOKEN), upLoadStoreId, this);
        showPopupWindow(getActivity(), R.id.title_bar_left_btn);
        mAddressAPI.getAddress();
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        hidePopupWindow();
        Address mAddress = mAddressAPI.parseJson(responseJson);
        if (mAddress == null) return;
        SharedPreferencesHelper.saveAddress(mAddress, SharePreferenceKeys.CURRENT_ADDRESS);
        EventBus.getDefault().post(new ShowAdSelectChange());

        Intent intent = new Intent(getActivity(), YMXMainActivity.class);
        intent.putExtra(YMXMainActivity.TAB_INDEX_KEY, YMXMainActivity.TAB_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        getActivity().finish();
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        hidePopupWindow();
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(null);
    }
}
